<template>
  <div style="padding-bottom:60px;">
    <SearchPartBJ :storageType="storageType" @dblclickPartInfo="setPartInfo" @selectRows="selectRows" />
    <!-- <PartInfoBJ ref="partInfo" :partInfoRow="partInfoRow" type="add" @getEditPartInfo="getEditPartInfo" /> -->
    <FormPanel ref="form" labelWidth="100" :cols="3" :list="formList" :isSubmitBtn="false"></FormPanel>
    <el-row class="btn-wrap">
      <el-button size="small" @click="$emit('cancel')">取消</el-button>
      <el-button type="primary" size="small" @click="confirmBtnClick">确定</el-button>
    </el-row>
  </div>
</template>

<script>
import { isAuthorized } from '@/utils/index';
import SearchPartBJ from './SearchPartBJ';
import { state, mutations } from './../store';
import { dictionary } from '@/utils/dictMixin';
import { getPartitionList } from '@/api/repair/repair/activitesManage';
// import PartInfoBJ from './PartInfo';
import { queryPartStock, searchTtRoLabour } from '@/api/part/partOutbound/repairMaterials/index.js';
// import PartInventory from './PartInventory';
import { getpartStocksList } from '@/api/part/inventoryManager/inventoryManager/index';

const jglx_dict = [
  { text: '终端建议零售VIP价格', value: 82481001, filedName: 'INSTRUCT_PRICE' },
  { text: '常规订货价', value: 82481002, filedName: 'PLAN_PRICE' },
  { text: '含税成本价', value: 82481003, filedName: 'COST_PRICE' },
  { text: '终端建议零售价格', value: 82481004, filedName: 'INSURANCE_PRICE' },
  { text: '索赔价', value: 82481005, filedName: 'CLAIM_PRICE' },
  { text: '最新进货价', value: 82481006, filedName: 'LATEST_PRICE' }
];

export default {
  name: 'wxll_add',
  mixins: [dictionary],
  components: {
    SearchPartBJ
    // PartInfoBJ
    // PartInventory
  },
  props: {
    storageType: {
      type: String
    }
  },
  data() {
    this.state = state;
    this.chargePartitionList = [];
    return {
      partInfoRow: {},
      isShowPartInventory: false,
      partStockDetail: {},
      stockFlag: false,
      selectList: [],
      formList: this.createList()
    };
  },
  mounted() {
    window.cgrk_add = this;
    console.log('采购入库 新增 mounted');
    this.getSystemAuthority();
    this.getPartitionList();
  },
  methods: {
    // 确定按钮
    confirmBtnClick() {
      // 收集表单数据 触发 getEditPartInfo 方法
      let res = this.$refs.form.SUBMIT_FORM();
      if (!this.selectList || this.selectList.length < 1) {
        this.$notify({
          title: '警告',
          message: '请选择配件',
          type: 'warning'
        });
        return;
      }
      let list = JSON.parse(JSON.stringify(this.selectList));
      let isCount = true;
      list.forEach(item => {
        this.formList.forEach(x => {
          switch (x.fieldName) {
            case 'IS_MAIN_PART':
              item[x.fieldName] = x.initialValue || 10041002;
              break;
            case 'PRICE_TYPE':
              if (!x.initialValue || x.initialValue == '') {
                this.$notify({
                  title: '警告',
                  message: '请选择价格类型',
                  type: 'warning'
                });
                isCount = false;
              } else {
                item[x.fieldName] = x.initialValue;
              }
              break;
            case 'CHARGE_PARTITION_CODE':
              if (!x.initialValue || x.initialValue == '') {
                this.$notify({
                  title: '警告',
                  message: '请选择收费区分',
                  type: 'warning'
                });
                isCount = false;
              } else {
                item[x.fieldName] = x.initialValue;
              }
              break;
            case 'LABOUR_CODE':
              if (!x.initialValue || x.initialValue == '') {
                this.$notify({
                  title: '警告',
                  message: '请选择维修项目',
                  type: 'warning'
                });
                isCount = false;
              } else {
                item[x.fieldName] = x.initialValue;
              }
              break;
            case 'PART_QUANTITY':
              if (!x.initialValue || x.initialValue == '') {
                this.$notify({
                  title: '警告',
                  message: '请输入数量',
                  type: 'warning'
                });
                isCount = false;
              } else {
                item[x.fieldName] = x.initialValue;
              }
              console.log(item[x.fieldName], '数量:::');
              break;
          }
        });
        const filedName = jglx_dict.find(x => x.value == item.PRICE_TYPE).filedName;
        const PRICE_TYPE = item[filedName] || 0; // 默认是1
        const PART_SALES_PRICE = Number(PRICE_TYPE) * 1;
        item.PART_SALES_PRICE = PART_SALES_PRICE;
        item.PRICE_RATE = 1;
        item.UNIT_NAME = item.UNIT_NAME || item.UNIT_CODE;
        item.USEABLE_STOCK = item.USEABLE_QUANTITY;
        item.CHARGE_PARTITION_NAME = this.chargePartitionList.find(x => x.value == item.CHARGE_PARTITION_CODE).text;
        item.PART_SALES_AMOUNT = (Number(item.PART_SALES_PRICE) * Number(item.PART_QUANTITY)).toFixed(2);
      });
      if (isCount) {
        this.$emit('confirm', list);
      }
    },
    selectRows(rows) {
      this.selectList = rows;
      console.log('addPanel::', this.selectList);
    },
    // 整合后的配件信息
    setPartInfo(partInfo) {
      console.log('整合后的配件信息 浅拷贝', JSON.stringify(partInfo, null, 2));
      this.partInfoRow = partInfo;
      // this.$refs.partInfo.initDataSource(partInfo);
    },
    // 收集 表单数据回调
    getEditPartInfo(partInfo) {
      console.log(partInfo, 'partInfo');
      if (partInfo.PRICE_RATE < 1) {
        if (isAuthorized('1313', '8248')) {
          console.log('表单数据', JSON.stringify(partInfo, null, 2));
          // 给父表加的数据
          this.$emit('confirm', partInfo);
        } else {
          this.$notify({
            title: '警告',
            message: '价格系数小于1，您无权限保存',
            type: 'warning'
          });
        }
      } else {
        this.$emit('confirm', partInfo);
      }
    },
    // 库存明细
    async stockDetail() {
      // if(this.partInfoRow)
      if (JSON.stringify(this.partInfoRow) != '{}') {
        let param = {
          PART_NO: this.partInfoRow.PART_NO,
          STORAGE_CODE1: this.partInfoRow.STORAGE_CODE,
          STORAGE_POSITION_CODE: this.partInfoRow.STORAGE_POSITION_CODE
        };
        let res = await getpartStocksList(param);
        this.partStockDetail = res.data.rows[0];
        this.isShowPartInventory = true;
      } else {
        this.$message({
          showClose: true,
          message: '请先选择一条配件信息',
          type: 'warning'
        });
      }
    },
    createList() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '仓库名称',
        //   fieldName: 'STORAGE_CODE',
        //   initialValue: '',
        //   placeholder: '',
        //   // itemList: state.dict_ck,
        //   itemList: [],
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '配件代码',
        //   fieldName: 'PART_NO',
        //   initialValue: '',
        //   placeholder: '',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '配件名称',
        //   fieldName: 'PART_NAME',
        //   initialValue: '',
        //   placeholder: '',
        //   disabled: true
        // },
        {
          type: 'SELECT',
          label: '主要配件',
          fieldName: 'IS_MAIN_PART',
          initialValue: 10041002,
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '价格类型',
          fieldName: 'PRICE_TYPE',
          placeholder: '',
          itemList: this.createDictList('8248'),
          rules: [{ type: 'number', required: true, message: '请选择价格类型', trigger: ['blur', 'change'] }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          fieldName: 'PRICE_RATE',
          hidden: true,
          rules: [{ required: true, message: '请输入价格系数', trigger: 'blur' }],
          precision: 2,
          initialValue: '1',
          placeholder: '',
          min: 1
        },
        {
          type: 'INPUT_NUMBER',
          label: '发料数量',
          fieldName: 'PART_QUANTITY',
          precision: 2,
          initialValue: 1,
          placeholder: '',
          rules: [{ type: 'number', required: true, message: '请输入配件数量', trigger: ['blur', 'change'] }]
        },
        {
          type: 'INPUT',
          label: '发料金额',
          fieldName: 'PART_SALES_AMOUNT',
          precision: 2,
          initialValue: '',
          placeholder: '',
          hidden: true
        },
        {
          type: 'SELECT',
          label: '收费区分',
          fieldName: 'CHARGE_PARTITION_CODE',
          initialValue: '',
          itemList: [],
          rules: [{ required: true, message: '请选择收费区分', trigger: ['blur'] }],
          change: val => {
            this.charge_partition_code_change(val);
          }
        },
        {
          type: 'SELECT',
          label: '维修项目',
          fieldName: 'LABOUR_CODE',
          initialValue: '',
          placeholder: '',
          itemList: state.dict_xlxm,
          change: val => {
            this.searchTtRoLabour(val);
          },
          rules: [{ type: 'string', required: true, message: '这是必填字段', trigger: ['blur', 'change'] }]
        }
        // {
        //   type: 'INPUT',
        //   label: '备注',
        //   fieldName: 'REMARK'
        // }
      ];
    },
    part_quantity_change(part_quantity) {
      var val = part_quantity;
      console.log('配件数量 PART_QUANTITY change', val);
      // 计算配件销售金额 (配件销售单价*配件数量)
      // const PART_SALES_PRICE = this.formList.find(x => x.fieldName === 'PART_SALES_PRICE').initialValue;
      const priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
      this.$nextTick(x => {
        this.calculateLogic(priceType);
      });
      // const PART_SALES_PRICE = this.partInfoRow['SALES_PRICE'] || 0;
      // console.log(part);
      // const PART_SALES_AMOUNT = Number(PART_SALES_PRICE) * Number(val);
      // this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = PART_SALES_AMOUNT.toFixed(2);
    },
    // 选择项目维修时改变的收费区分
    async searchTtRoLabour(val) {
      let LABOUR_CODE = val.split('~')[0];
      console.log(val, 'val');
      console.log(LABOUR_CODE, 'LABOUR_CODE');
      const res = await searchTtRoLabour({ roNo: state.roNo });
      res.data.rows.forEach((item, idx) => {
        if (item.LABOUR_CODE == LABOUR_CODE) {
          this.formList.find(x => x.fieldName == 'CHARGE_PARTITION_CODE').initialValue = res.data.rows[idx].CHARGE_PARTITION_CODE;
          this.charge_partition_code_change(res.data.rows[idx].CHARGE_PARTITION_CODE);
        }
      });
    },
    // 收费区分变化
    charge_partition_code_change(charge_partition_code) {
      console.log('收费区分 change', charge_partition_code);
      // a)选择免费时，价格类型自动选择索赔 82481005
      // b)选择自费时，价格类型自动选择终端建议零售VIP价格 82481001
      // c)选择保险时，价格类型自动选择终端建议零售价格 82481004
      // d)选择经销商时，价格类型自动选择成本价 82481003
      // 索赔 - 索赔 82481005

      // 82481001-终端建议零售VIP价格
      // 82481002-常规订货价
      // 82481003-含税成本价
      // 82481004-终端建议零售价格
      // 82481005-索赔价
      // 82481006-最新进货价
      let priceType = 82481001;
      let chargeName = this.chargePartitionList.find(x => x.value == charge_partition_code).text;
      if (chargeName == '免费') {
        // 免费 - 价格类型索赔
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481005;
      }
      if (chargeName == '自费') {
        // 自费
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481001;
      }
      if (chargeName == '保险') {
        // 保险
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481004;
      }
      if (chargeName == '经销商') {
        // 经销商
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481003;
      }
      if (chargeName == '索赔') {
        // 索赔
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481005;
      }
      // let priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
    },
    // 收费区分下拉框
    async getPartitionList() {
      const res = await getPartitionList();
      this.chargePartitionList = res.data.map(x => ({ value: x.CHARGE_PARTITION_CODE, text: x.CHARGE_PARTITION_NAME }));
      this.formList.find(x => x.fieldName == 'CHARGE_PARTITION_CODE').itemList = this.chargePartitionList;
    },
    // 获取系统权限
    getSystemAuthority() {
      // 库存明细
      let stockDetail = isAuthorized('1313', '13131012');
      console.log(stockDetail, 'stockDetailstockDetailstockDetail');
      if (stockDetail) {
        console.log('13131012----------------------------------');
        this.stockFlag = true;
      }
    }
  }
};
</script>

<style scoped>
.btn-wrap {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 9;
  border-top: 1px solid #e9e9e9;
  padding: 10px 20px;
  background: #fff;
  text-align: right;
}
</style>
